package com.bear.configurate;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LiuShanshan
 * @version V1.0
 * @Description
 */
@Configuration
@EnableWebSecurity
public class MyConfig extends WebSecurityConfigurerAdapter{//WebSecurityConfigurerAdapter 适配器



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login.html")
                .loginProcessingUrl("/login").permitAll()
                .defaultSuccessUrl("/ok", true).permitAll() //成功跳转的页面
                .passwordParameter("username")
                .usernameParameter("password")
                // 报错之后处理方法
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        System.out.println("密码错误");
                        e.printStackTrace();
                        // 判断异常信息 跳转不同页面 比如 密码过期重置
                        request.getRequestDispatcher(request.getRequestURL().toString()).forward(request, response);
                    }
                })
                .and()
                .csrf()   //下发token todo 如果没有，则加入另一行代码
                .csrfTokenRepository(new HttpSessionCsrfTokenRepository());
    }


    // 用户和密码进行加密
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    // 密码校验和用户赋权
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.
                inMemoryAuthentication()
                .withUser("123").password(new BCryptPasswordEncoder().encode("123")).roles("admin")
                .and()
                .withUser("321").password("321").roles("user");
    }




}
